/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package esnipe2;

import java.util.Calendar;

/**
 *
 * @author hangsu
 */
public class EbayItem {
    
    /*
     * Normally, this function will make its status to RESULT_NOTEND
     * if its status became RESUT_UNKNOWN, no ItemRunnable should be created
     * NOTE: This entry point WILL block
     */
    public EbayItem(String url, EbayAPI api) {
        this.itemUrl = url;
        this.api = api;
        this.initItem();
    }
    
    /*
     * Should be set here: 
     *  -itemNo
     *  -itemName
     *  -currentPrice
     *  -endTime : NOT YET SUPPORTED
     *  -status
     * NOTE: this entry point WILL block
     */
    final public boolean initItem() {
        //use EbayAPI to get (itemName), currentPrice, endTime(NYS)
        if(!api.getItemInfo(this)) {
            this.status = ItemResult.RESULT_UNKNOWN;
            return false;
        }
                
        //parse itemNo
        this.itemNo = EbayItem.getItemNo(itemUrl);
        this.itemName = EbayItem.getItemName(itemUrl);
        /*These should be used once getItemInfo is implememted
        //set status
        if(this.endTime.after(Calendar.getInstance(TimeZone.getTimeZone("PST")))) {
            this.status = ItemResult.RESULT_NOTEND;
            return true;
        } else {
            this.status = api.getResult(this.itemUrl);
            assert this.status!=ItemResult.RESULT_NOTEND;
            return false;
        }*/
        this.status = ItemResult.RESULT_NOTEND;
        return true;
    }
    
    public static String getItemNo(String url) {
        int endIdx = url.indexOf("?pt=");
        if(endIdx == -1)
            return null;
        int idx=endIdx-1;
        while(idx>=0) {
            if(!Character.isDigit(url.charAt(idx)))
                break;
            idx--;
        }
        idx+=1;
        return url.substring(idx, endIdx);
    }

    public static String getItemName(String url) {
        int startIdx = url.indexOf("itm/")+4;
        int endIdx = url.indexOf("/", startIdx);
        return url.substring(startIdx, endIdx).replace('-', ' ');
    }
    
    /*url pointing to the item*/
    public String itemUrl;
    
    /*item number from ebay(also in url), acts as its unique identity;*/
    public String itemNo;
    
    /*fields getting from websit using api*/
    public String itemName;
    public Pricepair currentPrice;
    public Calendar endTime;
    
    /*current item status*/
    public ItemResult status;
    
    /*api for item information*/
    private EbayAPI api;
    
}
